package com.unittec.drainage.provider.auth.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.unittec.drainage.provider.auth.dto.SysPermissionTree;
import com.unittec.drainage.provider.auth.entity.SysPermission;
import com.unittec.drainage.provider.auth.entity.SysPermissionDataRule;
import com.unittec.drainage.provider.auth.service.SysPermissionDataRuleService;
import com.unittec.drainage.provider.auth.service.SysPermissionService;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.request.Req101301;
import com.unittec.drainage.sdk.auth.request.Req101302;
import com.unittec.drainage.sdk.auth.request.Req101303;
import com.unittec.drainage.sdk.auth.request.Req101304;
import com.unittec.drainage.sdk.auth.request.Req101305;
import com.unittec.drainage.sdk.auth.request.Req101306;
import com.unittec.drainage.sdk.auth.request.Req101307;
import com.unittec.drainage.sdk.auth.request.Req101308;
import com.unittec.drainage.sdk.auth.request.Req101309;
import com.unittec.drainage.sdk.auth.request.Req101310;
import com.unittec.drainage.sdk.auth.response.Res101301;
import com.unittec.drainage.sdk.auth.response.Res101302;
import com.unittec.drainage.sdk.auth.response.Res101303;
import com.unittec.drainage.sdk.auth.response.Res101304;
import com.unittec.drainage.sdk.auth.response.Res101305;
import com.unittec.drainage.sdk.auth.response.Res101306;
import com.unittec.drainage.sdk.auth.response.Res101307;
import com.unittec.drainage.sdk.auth.response.Res101308;
import com.unittec.drainage.sdk.auth.response.Res101309;
import com.unittec.drainage.sdk.auth.response.Res101310;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.common.CommonConstant;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;
import com.unittec.drainage.sdk.root.enums.BizCodeEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author chengjie
 * @description 菜单管理
 * @date 2019/10/21
 */
@RestController
@Api(tags = "菜单管理")
public class SysPermissionController {

    @Autowired
    Log log;

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysPermissionDataRuleService sysPermissionDataRuleService;

    @RequestMapping(value = "/101301", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有菜单", notes = "查询所有菜单")
    @ResponseBody
    public Result<Res101301> list(@RequestBody GatewayRequest<Req101301> req) {
        log.debug(req, "list {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101301 res101301 = null;
        try {
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            if (StringUtils.isNotBlank(req.getContent().getPlatformCode())) {
                query.apply("FIND_IN_SET( {0}, platform_code )", req.getContent().getPlatformCode());
            }
            query.eq(SysPermission::getDelFlag, CommonConstant.DELETE_NO);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            List<SysPermissionTree> treeList = new ArrayList<SysPermissionTree>();
            getTreeList(treeList, list, null);
            res101301 = new Res101301();
            res101301.setList(treeList);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "list {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101301);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    private void getTreeList(List<SysPermissionTree> treeList, List<SysPermission> metaList, SysPermissionTree temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            SysPermissionTree tree = new SysPermissionTree(permission);
            if (temp == null && StringUtils.isBlank(tempPid)) {
                treeList.add(tree);
                if (!tree.isLeaf()) {
                    getTreeList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
                temp.getChildren().add(tree);
                if (!tree.isLeaf()) {
                    getTreeList(treeList, metaList, tree);
                }
            }
        }
    }

    @RequestMapping(value = "/101302", method = RequestMethod.POST)
    @ApiOperation(value = "添加菜单", notes = "添加菜单")
    @ResponseBody
    public Result<Res101302> addPermission(@RequestBody GatewayRequest<Req101302> req) {
        log.debug(req, "addPermission {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101302 res101302 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysPermission sysPermission = new SysPermission();
            BeanUtils.copyProperties(req.getContent(), sysPermission);
            sysPermissionService.addPermission(sysPermission);
            res101302 = new Res101302();
            res101302.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101302", JSON.toJSONString(req), "添加菜单", log.buildErrmsg(e),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "addPermission {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101302", JSON.toJSONString(req), "添加菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101302);
        } else {
            log.addOperateLog("101302", JSON.toJSONString(req), "添加菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101303", method = RequestMethod.POST)
    @ApiOperation(value = "修改菜单", notes = "修改菜单")
    @ResponseBody
    public Result<Res101303> updatePermission(@RequestBody GatewayRequest<Req101303> req) {
        log.debug(req, "updatePermission {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101303 res101303 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String id = req.getContent().getId();
            SysPermission sysPermission = sysPermissionService.getById(id);
            if (sysPermission != null) {
                BeanUtils.copyProperties(req.getContent(), sysPermission);
                sysPermissionService.editPermission(sysPermission);
                res101303 = new Res101303();
                res101303.setIsSuccess(true);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_PERMISSION;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101303", JSON.toJSONString(req), "修改菜单", log.buildErrmsg(e),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "updatePermission {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101303", JSON.toJSONString(req), "修改菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101303);
        } else {
            log.addOperateLog("101303", JSON.toJSONString(req), "修改菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101304", method = RequestMethod.POST)
    @ApiOperation(value = "批量删除菜单", notes = "批量删除菜单")
    @ResponseBody
    public Result<Res101304> deleteBatch(@RequestBody GatewayRequest<Req101304> req) {
        log.debug(req, "deleteBatch {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101304 res101304 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String ids = req.getContent().getIds();
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (StringUtils.isNotEmpty(id)) {
                    SysPermission sysPermission = sysPermissionService.getById(id);
                    if (sysPermission != null) {
                        sysPermissionService.deletePermission(sysPermission);
                    }
                }
            }
            res101304 = new Res101304();
            res101304.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101304", JSON.toJSONString(req), "批量删除菜单", log.buildErrmsg(e),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "deleteBatch {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101304", JSON.toJSONString(req), "批量删除菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101304);
        } else {
            log.addOperateLog("101304", JSON.toJSONString(req), "批量删除菜单", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101305", method = RequestMethod.POST)
    @ApiOperation(value = "查看菜单详情", notes = "查看菜单详情")
    @ResponseBody
    public Result<Res101305> details(@RequestBody GatewayRequest<Req101305> req) {
        log.debug(req, "details {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101305 res101305 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String id = req.getContent().getId();
            SysPermission sysPermission = sysPermissionService.getById(id);
            if (sysPermission != null) {
                res101305 = new Res101305();
                BeanUtils.copyProperties(sysPermission, res101305);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_PERMISSION;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "details {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101305);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101306", method = RequestMethod.POST)
    @ApiOperation(value = "查询菜单数据权限", notes = "查询菜单数据权限")
    @ResponseBody
    public Result<Res101306> queryPermissionRule(@RequestBody GatewayRequest<Req101306> req) {
        log.debug(req, "queryPermissionRule {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101306 res101306 = null;
        try {
            SysPermissionDataRule sysPermissionDataRule = new SysPermissionDataRule();
            BeanUtils.copyProperties(req.getContent(), sysPermissionDataRule);
            List<SysPermissionDataRule> list = sysPermissionDataRuleService.queryPermissionRule(sysPermissionDataRule);
            res101306 = new Res101306();
            res101306.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "queryPermissionRule {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101306);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101307", method = RequestMethod.POST)
    @ApiOperation(value = "菜单数据权限详情", notes = "菜单数据权限详情")
    @ResponseBody
    public Result<Res101307> getPermissionDataRuleDetails(@RequestBody GatewayRequest<Req101307> req) {
        log.debug(req, "getPermissionDataRuleDetails {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101307 res101307 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysPermissionDataRule sysPermissionDataRule =
                sysPermissionDataRuleService.getById(req.getContent().getId());
            if (sysPermissionDataRule != null) {
                res101307 = new Res101307();
                BeanUtils.copyProperties(sysPermissionDataRule, res101307);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_PERMISSION_DATA_RULE;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getPermissionDataRuleDetails {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101307);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101308", method = RequestMethod.POST)
    @ApiOperation(value = "添加菜单数据权限", notes = "添加菜单数据权限")
    @ResponseBody
    public Result<Res101308> addPermissionDataRule(@RequestBody GatewayRequest<Req101308> req) {
        log.debug(req, "getPermissionDataRuledetails {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101308 res101308 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysPermissionDataRule sysPermissionDataRule = new SysPermissionDataRule();
            BeanUtils.copyProperties(req.getContent(), sysPermissionDataRule);
            sysPermissionDataRuleService.savePermissionDataRule(sysPermissionDataRule);
            res101308 = new Res101308();
            res101308.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101308", JSON.toJSONString(req), "添加菜单数据权限", log.buildErrmsg(e),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "getPermissionDataRuledetails {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101308", JSON.toJSONString(req), "添加菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101308);
        } else {
            log.addOperateLog("101308", JSON.toJSONString(req), "添加菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101309", method = RequestMethod.POST)
    @ApiOperation(value = "修改菜单数据权限", notes = "修改菜单数据权限")
    @ResponseBody
    public Result<Res101309> updatePermissionDataRule(@RequestBody GatewayRequest<Req101309> req) {
        log.debug(req, "updatePermissionDataRule {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101309 res101309 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysPermissionDataRule sysPermissionDataRule =
                sysPermissionDataRuleService.getById(req.getContent().getId());
            if (sysPermissionDataRule != null) {
                BeanUtils.copyProperties(req.getContent(), sysPermissionDataRule);
                sysPermissionDataRuleService.updateById(sysPermissionDataRule);
                res101309 = new Res101309();
                res101309.setIsSuccess(true);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_PERMISSION_DATA_RULE;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101309", JSON.toJSONString(req), "修改菜单数据权限", log.buildErrmsg(e),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "updatePermissionDataRule {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101309", JSON.toJSONString(req), "修改菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101309);
        } else {
            log.addOperateLog("101309", JSON.toJSONString(req), "修改菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101310", method = RequestMethod.POST)
    @ApiOperation(value = "删除菜单数据权限", notes = "删除菜单数据权限")
    @ResponseBody
    public Result<Res101310> deletePermissionDataRule(@RequestBody GatewayRequest<Req101310> req) {
        log.debug(req, "deletePermissionDataRule {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101310 res101310 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysPermissionDataRule sysPermissionDataRule =
                sysPermissionDataRuleService.getById(req.getContent().getId());
            if (sysPermissionDataRule != null) {
                sysPermissionDataRuleService.removeById(sysPermissionDataRule.getId());
                res101310 = new Res101310();
                res101310.setIsSuccess(true);
                bizCodeEnum = BizCode.SUCCESS;
            } else {
                bizCodeEnum = BizCode.NOT_PERMISSION_DATA_RULE;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101310", JSON.toJSONString(req), "删除菜单数据权限", log.buildErrmsg(e),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "deletePermissionDataRule {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101310", JSON.toJSONString(req), "删除菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101310);
        } else {
            log.addOperateLog("101310", JSON.toJSONString(req), "删除菜单数据权限", bizCodeEnum.getMessage(),
                LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

}
